/**
 * @Description: APP基础类
 * @author tao.xie
 * @date $
 */

import React, { Component } from 'react'
import { isUserLogin } from '../utils/UserBean'

export default class XBBaseAppPage extends Component {
  constructor (props) {
    super(props)

    this.state = {
      needToRefresh: false,
      isLogin: false
    }

    this._willFocusSubscription = null
    this._willBlurSubScription = null
  }

  _initLoginState = async () => {
    let isLogin = await isUserLogin()
    this.setState({ isLogin: isLogin })
  }

  /**
   * 当登录状态切换时，调用该方法。子类需继承
   * @private
   */
  _refreshWhenLoginStateChanged = () => {
  }

  /**
   * 返回刷新，调用该方法。子类需继承
   * @private
   */
  _refreshOnResume = () => {

  }

  _dispathWhenFocused = async () => {
    let isLogin = await isUserLogin()
    if (isLogin === this.state.isLogin) {
      if (this.state.needToRefresh === true) {
        this.setState({ needToRefresh: false })
        this._refreshOnResume()
      }
    } else {
      this.setState({ isLogin: isLogin })
      this.setState({ needToRefresh: false })
      this._refreshWhenLoginStateChanged(this.state.isLogin)
    }
  }

  componentWillUnmount (): void {
    this._willFocusSubscription && this._willFocusSubscription.remove()
    this._willBlurSubScription && this._willBlurSubScription.remove()
  }

  componentWillMount (): void {
    this._initLoginState()

    this._willFocusSubscription = this.props.navigation.addListener('willFocus', () => {
      this._dispathWhenFocused()
    })
    this._willBlurSubScription = this.props.navigation.addListener('willBlur', () => {
      this.setState({ needToRefresh: true })
    })
  }
}
